/* vue */
import VC from '@model/VC'
import { Ref, Component, Prop } from 'vue-property-decorator'
import { CreateElement } from 'vue'

/* components */
import { Table } from 'element-ui'
import TaskAllotServiceProvider from '@src/modules/task/components/TaskAllotModal/TaskAllotServiceProvider/TaskAllotServiceProvider'

/* scss */
import '@src/modules/task/components/TaskAllotModal/TaskAllotServiceProvider/Table/Table.scss'

/* modal */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
import TaskAllotModal from '@src/modules/task/components/TaskAllotModal/TaskAllotModal'
import Column from '@model/types/Column'
import { TaskAllotServiceProviderInfo } from '@src/modules/task/components/TaskAllotModal/TaskAllotServiceProvider/TaskAllotServiceProviderModel'
import { TaskAllotTableColumnFieldEnum,TableColumnDefaultWidth, AreaInfoEnum } from '@src/modules/task/components/TaskAllotModal/TaskAllotServiceProvider/Table/TableModel'

/* util */
import { uuid } from 'pub-bbx-utils'
import { isString } from '@src/util/type'
import { fmt_display_text, fmt_datetime } from '@src/filter/fmt'
import { isArray } from 'lodash'
import { findComponentUpward, findComponentDownward } from '@src/util/assist'
import i18n from '@src/locales'

@Component({
  name: ComponentNameEnum.TaskAllotServiceProviderTable,
  components: {}
})
export default class TaskAllotServiceProviderTable extends VC {
  /* 工单派单服务商表格组件 */
  @Ref() TaskAllotServiceProviderElTableComponent !: Table

  /* 选择列 组件 */
  get BaseTableAdvancedSettingComponent(): any {
    return findComponentDownward(this, ComponentNameEnum.BaseTableAdvancedSetting)
  }

  /* 工单信息 */
  get task(): any {
    // @ts-ignore
    return this.TaskAllotModalComponent?.task || {}
  }
  /* 工单派单组件 */
  get TaskAllotModalComponent(): TaskAllotModal {
    return findComponentUpward(this, ComponentNameEnum.TaskAllotModal) || {}
  }
  /* 工单派单服务商组件 */
  get TaskAllotServiceProviderComponent(): TaskAllotServiceProvider {
    return findComponentUpward(this, ComponentNameEnum.TaskAllotServiceProvider) || {}
  }

  /* 表格列 */
  @Prop() readonly columns: Column[] | undefined
  /* 拖动变化方法 */
  @Prop() readonly dragendFunc: Function | undefined
  /* 是否禁用加载更多 */
  @Prop() readonly isDisableLoadmore: boolean | undefined
  /* 排序变化方法 */
  @Prop() readonly sortChangeFunc: Function | undefined
  /* 表格高度 */
  @Prop() readonly tableHeight: string | undefined
  /* 服务商选择状态 */
  @Prop() readonly serviceProviderPageCheckedMap: { [x: number]: boolean } | undefined
  /**/
  @Prop() readonly assignToEngineerEnable: boolean | undefined
  /* 表格key 随机数 */
  public tableKey: number | string = Math.random() * 1000 >> 2
  /* 工单指派服务商列表 */
  public taskAllotServiceProviderList: TaskAllotServiceProviderInfo[] = []

  /** 
   * @description 表格拖动事件
  */
  public handlerHeaderDragend(newWidth: number, oldWidth: number, tableColumn: any = {}) {
    this.dragendFunc && this.dragendFunc(newWidth, oldWidth, tableColumn)
  }
  /** 
   * @description 选择排序方式变化事件
  */
  public handlerTableSortChanged(option: { prop?: any, order?: any } = {}) {
    this.sortChangeFunc && this.sortChangeFunc(option)
  }
  /** 
   * @description 设置服务商checkbox 变化
  */
  public handlerServiceProviderCheckedChange(checked: boolean, row: TaskAllotServiceProviderInfo): void {
    /* 设置负责人信息 */
    this.TaskAllotServiceProviderComponent?.outsideUpwardSetServiceProvider(checked, row)
  }


  /** 
   * @description 设置工单指派人员列表信息
   * -- 支持向上的外部调用的方法
  */
  public outsideSetServiceProviderPage(serviceProviderList: TaskAllotServiceProviderInfo[]) {
    this.taskAllotServiceProviderList = serviceProviderList
  }

  /** 
 * @description 渲染表格列
*/
  public renderTableColumnField(scope: any, column: Column) {
    let value = column.field ? scope.row[column.field] : ''
    let isMain = scope.row?.isMain || false

    if(column.field === 'authorizedArea'){
      let authorizedArea =  scope.row[column.field] || []
      if(authorizedArea?.length){
        let area:string[] = []
        authorizedArea.forEach((item:AreaInfoEnum) => {
          let addres = []
          if(item.province){
            addres.push(item.province)
          }
          if(item.city){
            addres.push(item.city)
          }
          if(item.dist){
            addres.push(item.dist)
          }
          area.push(addres.join('-'))
        });
        value = area
      }
      return this.renderColumnTip(value)
    }
    // s-自定义字段
    // 地址
    if (column?.formType === 'address') return value?.all || '--';
    // 人员
    if (column?.formType === 'user') return (value || []).map((item: any) => item.displayName).join(', ') || '--';
    // 多级菜单
    if (column?.formType ==='cascader') return (value || []).join('/') || '--';
    // e-自定义字段
    // 服务商
    if (column.field === TaskAllotTableColumnFieldEnum.UserId) return this.renderColumnWithServiceProvider(scope)
    // 数组类型
    let isStringArray = Array.isArray(value) && value.every(item => isString(item))
    if (isStringArray) return this.renderColumnWithStringArray(value)
    // 距离
    if (column.field === TaskAllotTableColumnFieldEnum.Distance) return this.renderColumnWithDistance(value);
    if (column.field === TaskAllotTableColumnFieldEnum.Username && this.assignToEngineerEnable && isMain) return this.renderColumnWithUserName(value);
    // 上岗日期
    if (column.field === TaskAllotTableColumnFieldEnum.EngineerDate) return fmt_datetime(value) || '--';
    // 授权有效期
    if (column.field === TaskAllotTableColumnFieldEnum.ValidTime) return value? `${fmt_datetime(value?.validTime)} - ${fmt_datetime(value?.inalidTime)}` : '--';
    // 角色
    if (column.field === TaskAllotTableColumnFieldEnum.Role) return value?.name || '';
    return this.renderColumnWithCommon(value)
  }

  /** 
   * @description 渲染通用表格列
  */
  public renderColumnWithCommon(value: string) {
    return fmt_display_text(value)
  }

  /** 
   * @description 渲染数组表格列
  */
  public renderColumnWithStringArray(value: string[]): string {
    return isArray(value) ? value.join(', ') : fmt_display_text(value)
  }

  public renderColumnTip(value: any){
    let data = value?.join(',')
   
    return (
    <el-tooltip class="item" effect="dark" content={data} placement="top">
      <div class="TableInfo"> { data }</div>
    </el-tooltip>
    )
  } 
  /** 
   * @description 渲染服务商表格列
  */
  public renderColumnWithServiceProvider(scope: any) {
    let { userId = '' } = scope.row

    return (
      <div class='task-allot-user-table-excutor-column'>
        <el-checkbox
          value={this.serviceProviderPageCheckedMap?.[userId]}
          onInput={(value: boolean) => this.handlerServiceProviderCheckedChange(value, scope.row)}
        >
        </el-checkbox>
      </div>
    )
  }

  /**
   * @description 渲染服务商距离
   */
  public renderColumnWithDistance(value: string, row: any = {}) {
    let distance = Number(value)
    if (isNaN(distance)) return value
    return distance ? `${(distance / 1000).toFixed(2)}` : fmt_display_text(distance)
  }

  /**
   * @description 渲染工程师
   */
  public renderColumnWithUserName(value: string, row: any = {}) {
    return (
        <div>
          {value}
          <el-tag style={'margin-left: 4px'}>
            {i18n.t('common.base.principal')}
          </el-tag>
        </div>
    )
  }

  /** 
   * @description 渲染表格插入 用于无限加载显示
  */
  public renderTableAppendSlot() {
    if (this.taskAllotServiceProviderList.length <= 0) return null
    return (
      <div class='task-allot-user-table-append-block'>{this.isDisableLoadmore ? i18n.t('task.components.taskAllotModal.allResultsLoaded') : i18n.t('common.base.loadMore')}</div>
    )
  }

  render(h: CreateElement) {
    return (
      <div class={ComponentNameEnum.TaskAllotUserTable}>
        <div class='task-allot-user-table-block' id="ProviedTable">
          <el-table
            border
            data={this.taskAllotServiceProviderList}
            height={this.tableHeight}
            header-row-class-name='base-table-header-v3'
            row-class-name='base-table-row-v3'
            ref='TaskAllotServiceProviderElTableComponent'
            key={this.tableKey}
            rowKey={uuid()}
            onHeader-dragend={(newWidth: number, oldWidth: number, column: any) => this.handlerHeaderDragend(newWidth, oldWidth, column)}
            onSort-change={(option: any) => this.handlerTableSortChanged(option)}
            stripe
            scopedSlots={{ append: () => this.renderTableAppendSlot() }}
          >
            {
              this.columns && this.columns.filter((column: Column) => column.show).map((column: Column) => {
                return (
                  <el-table-column
                    label={column.label}
                    key={column.field}
                    minWidth={column.width ? `${column.width}px` : TableColumnDefaultWidth}
                    prop={column.field}
                    resizable={true}
                    sortable={column.sortable}
                    showOverFlowTooltip={true}
                  >
                    {(scope: any) => this.renderTableColumnField(scope, column)}
                  </el-table-column>
                )
              })

            }
            <div slot='append'></div>
          </el-table>
        </div>
      </div>
    )
  }
}
